﻿namespace npantarhei.contrib
{
	using System;
	using System.Collections.Generic;
	using System.ComponentModel.Composition.Hosting;
	using System.ComponentModel.Composition.Primitives;
	using System.Linq;
	using npantarhei.contrib.mef;
	using npantarhei.runtime;

	public static class FlowRuntimeConfigurationExtensions
	{
		public static void Configure(this FlowRuntimeConfiguration frc, CompositionContainer container)
		{
			foreach (var stream in frc.Streams)
			{
				var contractName = stream.ToPort.OperationName;
				var importDefinition = BuildImportDefinition(contractName);
				IEnumerable<Export> exports;

				if (!container.TryGetExports(importDefinition, new AtomicComposition(), out exports))
				{
					continue;
				}

				frc.AddOperation(new ExportedOperation(exports.First(), contractName));
			}
		}

		private static ImportDefinition BuildImportDefinition(string contractName)
		{
			var importDefinition =
				new ImportDefinition(
					definition =>
						string.Compare(contractName, definition.Metadata["Name"].ToString(), StringComparison.InvariantCultureIgnoreCase) == 0,
					contractName,
					ImportCardinality.ExactlyOne,
					false,
					false);

			return importDefinition;
		}
	}
}